package spring.service;


import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import spring.dao.UserMapper;
import spring.pojo.User;
import spring.tools.DBTools;

import java.util.List;

public class UserServiceTest {
    @Test
    //添加操作
    public void insertUser() throws Exception {
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = new User("车厘子", "666666", 99999.9);
        try {
            mapper.insertUser(user);
            System.out.println(user.toString());
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
    }

    @Test
    //删除操作
    public void deleteUser() throws Exception {
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        try {
            int result = mapper.deleteUser(3);
            session.commit();
            System.out.println("result:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
    }

    @Test
//修改操作
    public void updateUser() throws Exception  {
        SqlSession session=DBTools.getSession();
        UserMapper mapper=session.getMapper(UserMapper.class);

        try {
            User user = mapper.selectUserById(2);
            user.setUsername("猕猴桃");
            user.setPassword("666666666");
            System.out.println("result:" + user);

            int result=mapper.updateUser(user);
            session.commit();
            System.out.println("result:" + result);

        }catch (Exception e){

            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }


    }


    @Test
    //选择操作
    public void selectUserById() throws Exception {
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        try {
            //这里用到User类的无参构造方法创建对象，User user=new User（）；
            User user = mapper.selectUserById(1);
            System.out.println(user.toString());

            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
    }

    @Test
    public void selectAllUser() throws Exception {
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        try {
            List<User> user = mapper.selectAllUser();
            System.out.println(user.toString());
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
    }

}
